package com.xh.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xh.core.util.CacheUtils;
import com.xh.core.util.StringUtils;
import com.xh.core.util.UserUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/*
 * @Author daiwei
 * @Description
 * @Date 2018/8/10 11:03
 **/
public class XhMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object creatorId = getFieldValByName("creatorId", metaObject);//mybatis-plus版本2.0.9+
        Object deleted = getFieldValByName("deleted", metaObject);//mybatis-plus版本2.0.9+
        Object createTime = getFieldValByName("createTime", metaObject);
        Object checked = getFieldValByName("checked", metaObject);
        if (creatorId == null) {
            JSONObject currentUser=(JSONObject) CacheUtils.get("user_"+ UserUtils.getCurrentUserId());
            String userId=UserUtils.getCurrentUserId();
            String name=null;
            if(currentUser!=null) {

                name = currentUser.getString("username");
                if (StringUtils.isEmpty(name)) {
                    name = currentUser.getString("nickname");
                }
            }

            setFieldValByName("creatorId",userId,metaObject);
            setFieldValByName("creatorName",name,metaObject);
        }
        setFieldValByName("modifierId",getFieldValByName("creatorId", metaObject),metaObject);
        setFieldValByName("modifierName",getFieldValByName("creatorName", metaObject),metaObject);

        Date now=new Date();
        if(createTime == null){
            setFieldValByName("createTime",now,metaObject);
        }else {
            setFieldValByName("createTime",createTime,metaObject);
        }

        setFieldValByName("modifyTime",now,metaObject);
        if(deleted==null){
            setFieldValByName("deleted",0,metaObject);
        }
        if(checked==null){
            setFieldValByName("checked",0,metaObject);
        }

    }

    /**
     * 修改填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        //更新填充
        Date now=new Date();
        JSONObject currentUser=(JSONObject) CacheUtils.get("user_"+ UserUtils.getCurrentUserId());
        String userId=UserUtils.getCurrentUserId();
        String name=null;
        if(currentUser!=null) {
            name = currentUser.getString("nickname");
        }
        setFieldValByName("modifierId",userId,metaObject);
        setFieldValByName("modifierName",name,metaObject);
        setFieldValByName("modifyTime",now,metaObject);
    }

}